const { exec } = require("child_process");
const path = require("path");
const JmxRuntime = require("./JmxRuntime");

class JmxExecutor {

    constructor(jmeterHomePath) {
        const jmeterExecutable = process.platform === "win32" ? "jmeter.bat" : "jmeter";
        this.jmeterExecutablePath = path.resolve(jmeterHomePath, "bin", jmeterExecutable);
    }

    /**
     * 
     * @param {JmxRuntime} jmxRuntime 
     */
    async execute(jmxRuntime) {
        let argument = `-n -t ${jmxRuntime.jmxFilePath}`;
        argument += ` -JthreadNumber=${jmxRuntime.threadNumber}`;
        argument += ` -Jduration=${jmxRuntime.duration}`;
        argument += ` -l ${jmxRuntime.jtlFilePath}`;
        argument += " -Jjmeter.save.saveservice.output_format=csv";
        argument += "-Jjmeter.save.saveservice.response_data=true";
        argument += " -Jjmeter.save.saveservice.response_headers=true";
        argument += " -Jjmeter.save.saveservice.samplerData=true";
        argument += " -Lorg.apache.jmeter=WARN";
        const command = `${this.jmeterExecutablePath} ${argument}`;
        return new Promise((resolve, reject) => {
            console.log(`${new Date().toISOString()}: [${jmxRuntime.testPlanName}, 并发数=${jmxRuntime.threadNumber}, 测试时间=${jmxRuntime.duration}s] 开始执行`);
            exec(command, { stdio: 'ignore' }, error => {
                if (error) {
                    console.error(`${new Date().toISOString()}: 执行 [${jmxRuntime.testPlanName}, 并发数=${jmxRuntime.threadNumber}, 测试时间=${jmxRuntime.duration}s] 失败: ${error.message}`);
                    reject(error);
                    return;
                }
                resolve();
                console.log(`${new Date().toISOString()}: [${jmxRuntime.testPlanName}, 并发数=${jmxRuntime.threadNumber}, 测试时间=${jmxRuntime.duration}s] 执行完成`);
            });
        });
    }

}

module.exports = JmxExecutor;